package models

import (
	"gorm.io/gorm"
)

type Live struct {
	gorm.Model
	Name  string `gorm:"type:varchar(20);not null;"`
	Begin string `gorm:"type:varchar(30);not null"`
	End   string `gorm:"type:varchar(30);not null"`
}

func (l *Live) List(keyword string, page, pageSize int) (list []Live, err error) {
	query := DB

	if keyword != "" {
		query = query.Where("name like ?", "%"+keyword+"%")
	}

	err = query.Scopes(Paginate(page, pageSize)).
		Find(&list).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 5
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func (l *Live) Create() error {
	return DB.Create(&l).Error
}

func (l *Live) Delete() error {
	return DB.Delete(&l).Error
}

func (l *Live) GetLiveById() error {
	return DB.Where("id=?", l.ID).Limit(1).Find(&l).Error
}
